# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iPlace import PlaceListGUI

class StaffGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Employé")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Staff-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Staff-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tStaffGUI\tStart")
		self.makeStaff()

	 # DEBUT de la gestion du module Staff --------------------------------------------------------------------------------------------------------------
	def clearFieldStaff(self):
		for value in self.staffValues:
			value.set("")
		# remise a zero des elements de recherche Place Staff
		self.gradeStaffCB.selectitem(1)
		self.staffValues[6].set(u"A")
		self.gradeStaffCB.selectitem(1) 
		self.staffValues[7].set(u"OT")
		self.listObject=[Place]

	def selectStaff(self, event):
		result = Staff.select(Staff.q.id==self.idListStaff[int(self.listStaff.curselection()[0])])
		for row in result:
			self.selectedStaff = row
		self.listObject[0] = self.selectedStaff.place
		if self.selectedStaff.fname != None:self.staffValues[1].set(self.selectedStaff.fname)
		self.staffValues[2].set(self.selectedStaff .lname)
		self.staffValues[3].set(self.selectedStaff .mname)
		self.staffValues[4].set(self.selectedStaff .username)
		self.staffValues[5].set(self.selectedStaff .password)
		self.staffValues[6].set(self.selectedStaff .status)
		self.staffValues[7].set(self.selectedStaff .grade)
		self.staffValues[0].set(self.listObject[0].company)
		# Affichage du Status dans la ComboBox
		status = ( (u"D", 0), (u"A", 1), (u"S", 2), )
		for n in status:
			if n[0] == self.selectedStaff .status: self.statusStaffCB.selectitem(n[1])
		# Affichage du Grade dans la ComboBox
		grade = ( (u"AD", 0), (u"MA", 1), (u"DM", 2),(u"TE", 3), (u"CL", 4),(u"RE", 5),(u"OT", 6),)
		for n in grade:
			if n[0] == self.selectedStaff .grade: self.gradeStaffCB.selectitem(n[1])
		# activation du bouton supprimer
		self.deleteStaffBt.config(state=NORMAL)

	def searchStaff(self, event=None):
		if self.searchStaffValue.get() != "":
			self.listStaff.delete(0,END)
			self.idListStaff = []
			result = Staff.select(Staff.q.lname.startswith(self.searchStaffValue.get().encode("utf-8")), orderBy=Staff.q.lname)
			for row in result:
				self.listStaff.insert(END, row.lname+" - "+row.fname)
				self.idListStaff.append(row.id)
		else:
			self.listStaff.delete(0,END)
			self.idListStaff = []
			result = Staff.select(orderBy=Staff.q.lname)
			for row in result:
				self.listStaff.insert(END, row.lname+" - "+row.fname)
				self.idListStaff.append(row.id)

	def makeStaff(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Employé").pack(fill=X)
		staffLabels = (u"Résidence", u"Prénom", u"Nom", u"Initiales", u"Utilisateur", u"Mot de passe", u"Status", u"Fonction")
		self.staffValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
		statusStaffCB = (u"Désactivé", u"Activé", u"Suspendu")
		gradeStaffCB = (u"Administrateur", u"Manager", u"Duty Manager", u"Technique", u"Ménage", u"Récéption", u"Autres")
		count = 0
		for name in staffLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0:  # Place
				Entry(f, textvariable=self.staffValues[count], state=DISABLED, bd=0, disabledforeground="black", width=31).pack(side=LEFT, fill=X)
				myPlace=Button(f,  image=self.imgSearch, command=lambda x=self.staffValues[count]:self.ctrlListPlace(x), padx=4, pady=1)
				myPlace.pack(side=RIGHT)
				self.balloon.bind(myPlace, u"Séléctionner une Résidence")
			elif count == 6: # Status
				self.statusStaffCB=Pmw.ComboBox(f, selectioncommand=self.staffStatus, scrolledlist_items=statusStaffCB, listheight=100)
				self.statusStaffCB._entryfield._entryFieldEntry.config( width = 31)
				self.statusStaffCB.pack(side=LEFT, fill=X)
				self.statusStaffCB.selectitem(1)
				self.staffValues[6].set(u"A")
			elif count == 7:  # Grade
				self.gradeStaffCB=Pmw.ComboBox(f, selectioncommand=self.staffGrade, scrolledlist_items=gradeStaffCB, listheight=100)
				self.gradeStaffCB._entryfield._entryFieldEntry.config( width = 31)
				self.gradeStaffCB.pack(side=LEFT, fill=X)
				self.gradeStaffCB.selectitem(6)   
				self.staffValues[7].set(u"OT")
			else: 
				Entry(f, textvariable=self.staffValues[count], width=34).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveStaffBt=Button(s, image=self.imgSave, command=self.createStaff)
		self.saveStaffBt.bind("<Return>", self.createStaff)
		self.saveStaffBt.pack(side=LEFT)
		self.balloon.bind(self.saveStaffBt, u"Enregistrer")
		self.deleteStaffBt=Button(s, image=self.imgDelete, command=self.deleteStaff, state=DISABLED)
		self.deleteStaffBt.bind("<Return>", self.deleteStaff)
		self.deleteStaffBt.pack(side=LEFT)
		self.balloon.bind(self.deleteStaffBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Employés").pack(side=TOP, fill=X)
		self.searchStaffValue = StringVar()
		self.searchStaffEt = Entry(leftFrame,  width=42, textvariable=self.searchStaffValue, relief=GROOVE)
		self.searchStaffEt.bind("<KeyRelease>", self.searchStaff)
		self.searchStaffEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchStaffEt, u"Saisir les premières lettres d'un employé\npour une recherche plus précise,\nla liste est classée par Nom.")
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listStaff = Listbox(s)
		self.listStaff.config(yscrollcommand=scrollbar.set,width=43, selectmode=SINGLE, height=16)
		self.listStaff.bind("<ButtonRelease-1>",self.selectStaff)
		scrollbar.config(command=self.listStaff.yview)
		self.listStaff.pack(side=TOP, fill=X)
		self.balloon.bind(self.listStaff, u"Séléctionner un employé\npour le visualiser ou le modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		self.listObject=[Place]
		self.searchStaff()

	def ctrlListPlace(self,field):
		PlaceListGUI(balloon=self.balloon, field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)

	def staffStatus(self, value):
		status = (  (u"D", u"Désactivé"), (u"A", u"Activé"), (u"S", u"Suspendu"), ) 
		for n in status:
			if n[1] == value: self.staffValues[6].set(n[0])
		
	def staffGrade(self, value):
		grade = (  (u"AD", u"Administrateur"), (u"MA", u"Manager"), (u"DM", u"Duty Manager"), (u"TE", u"Technique"), (u"CL", u"Ménage"), (u"RE", u"Récéption"), (u"OT", u"Autres"), ) 
		for n in grade:
			if n[1] == value: self.staffValues[7].set(n[0])

	def verifyStaff(self):
		if self.staffValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Résidence est obligatoire !\nMerci de le compléter.")
			return False
		elif self.staffValues[2].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Nom est obligatoire !\nMerci de le compléter.")
			return False
		elif self.staffValues[3].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Initiales est obligatoire !\nMerci de le compléter.")
			return False
		elif self.staffValues[4].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Utilisateur est obligatoire !\nMerci de le compléter.")
			return False
		elif self.staffValues[5].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Mot de passe est obligatoire !\nMerci de le compléter.")
			return False
		elif self.staffValues[6].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Status est obligatoire !\nMerci de le compléter.")
			return False
		elif self.staffValues[7].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Fonction est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createStaff(self, event=None):
		if self.verifyStaff():
			if  self.deleteStaffBt.config()["state"][4] == "normal":
				self.modifyStaff()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Employé ?\n" % self.staffValues[2].get()):
					Staff(place=self.listObject[0],
						fname=self.staffValues[1].get().encode("utf-8"),
						lname=self.staffValues[2].get().encode("utf-8"),
						mname=self.staffValues[3].get().encode("utf-8"),
						username=self.staffValues[4].get().encode("utf-8"),
						password=self.staffValues[5].get().encode("utf-8"),
						status=self.staffValues[6].get().encode("utf-8"),
						grade=self.staffValues[7].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchStaff()
				self.clearFieldStaff()

	def modifyStaff(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier l'Employé %s ?" % self.selectedStaff.lname):
			self.selectedStaff.place=self.listObject[0]
			self.selectedStaff.fname=self.staffValues[1].get().encode("utf-8")
			self.selectedStaff.lname=self.staffValues[2].get().encode("utf-8")
			self.selectedStaff.mname=self.staffValues[3].get().encode("utf-8")
			self.selectedStaff.username=self.staffValues[4].get().encode("utf-8")
			self.selectedStaff.password=self.staffValues[5].get().encode("utf-8")
			self.selectedStaff.status=self.staffValues[6].get().encode("utf-8")
			self.selectedStaff.grade=self.staffValues[7].get().encode("utf-8")
			self.searchStaff()
		self.deleteStaffBt.config(state=DISABLED)
		self.clearFieldStaff()

	def deleteStaff(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer l'Employé %s ?\nCette opération est irréversible !" % self.selectedStaff.lname):
			Staff.delete(self.selectedStaff.id)
			self.searchStaff()
		self.deleteStaffBt.config(state=DISABLED)
		self.clearFieldStaff()
	# FIN de la gestion du module Staff ---------------------------------------------------------------------------------------------------------------------

class StaffListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Employés")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		## # Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Staff-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Staff-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tStaffListGUI\tStart")
		self.makeListStaff()

	def selectListStaff(self, event):
		if self.listListStaff.get(0)!="":
			result = Staff.select(Staff.q.id==self.idListListStaff[int(self.listListStaff.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row .fname+" - "+row .lname)
				self.destroy()

	def searchListStaff(self, event=None):
		if self.searchListStaffValue.get() != "":
			self.listListStaff.delete(0,END)
			self.idListListStaff = []
			result = Staff.select(Staff.q.lname.startswith(self.searchListStaffValue.get().encode("utf-8")), orderBy=Staff.q.lname)
			for row in result:
				self.listListStaff.insert(END, row.lname+" - "+row.fname)
				self.idListListStaff.append(row.id)
		else:
			self.listListStaff.delete(0,END)
			self.idListListStaff = []
			result = Staff.select(orderBy=Staff.q.lname)
			for row in result:
				self.listListStaff.insert(END, row.lname+" - "+row.fname)
				self.idListListStaff.append(row.id)

	def makeListStaff(self,field=None,index=None):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des Employés").pack(side=TOP, fill=X)
		self.searchListStaffValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListStaffEt = Entry(s,  width=32, textvariable=self.searchListStaffValue, relief=GROOVE)
		self.searchListStaffEt.bind("<KeyRelease>", self.searchListStaff)
		self.searchListStaffEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListStaffEt, u"Saisir les premiéres lettres d'un employé\npour une recherche plus précise,\nla liste est classée par Nom.")
		newStaff=Button(s, image=self.imgNew, command=self.ctrlStaff)
		newStaff.pack(side=RIGHT)
		self.balloon.bind(newStaff, u"Créer un nouvel Employé")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListStaff = Listbox(s)
		self.listListStaff.config(yscrollcommand=scrollbar.set,width=33, selectmode=SINGLE, height=16)
		self.listListStaff.bind("<ButtonRelease-1>",self.selectListStaff)
		scrollbar.config(command=self.listListStaff.yview)
		self.listListStaff.pack()
		self.balloon.bind(self.listListStaff, u"Séléctionner un employé.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListStaff()
		
	def ctrlStaff(self):
		StaffGUI(balloon=self.balloon, log=self.log, path=self.path)